package cn.xxy.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressWarnings("unchecked")
public class ConvertUtils {
	public static final String FULL_DATE_ZH_FORMAT = "yyyy-MM-dd HH:mm:ss SSS";

	public static <T> T convert(String value, Class<T> clazz) {
		if (clazz == null) throw new IllegalArgumentException("类型不能为空");

		// if (clazz.isPrimitive()) throw new
		// IllegalArgumentException("转换的类型不能为基本类型");
		if (clazz == int.class) clazz = (Class<T>) Integer.class;
		if (clazz == long.class) clazz = (Class<T>) Long.class;
		if (clazz == float.class) clazz = (Class<T>) Float.class;
		if (clazz == double.class) clazz = (Class<T>) Double.class;
		if (clazz == boolean.class) clazz = (Class<T>) Boolean.class;

		if (value == null || clazz == Object.class) return (T) value;
		if (clazz == String.class) return (T) value;

		if (clazz == Integer.class) return (T) Integer.valueOf(value);
		if (clazz == Long.class) return (T) Long.valueOf(value);
		if (clazz == Float.class) return (T) Float.valueOf(value);
		if (clazz == Double.class) return (T) Double.valueOf(value);
		if (clazz == Boolean.class) return (T) Boolean.valueOf(value);
		if (clazz == Number.class) return (T) convert(value, Double.class);

		if (clazz == Date.class) {
			return (T) convertDate(value);
		}

		if (clazz == java.sql.Timestamp.class) {
			return (T) new java.sql.Timestamp(convert(value, Date.class).getTime());
		}

		if (clazz == java.sql.Date.class) {
			return (T) new java.sql.Date(convert(value, Date.class).getTime());
		}

		if (clazz == java.sql.Time.class) {
			return (T) new java.sql.Time(convert(value, Date.class).getTime());
		}
		throw new RuntimeException("不支持的类型转换 : String ==> " + clazz.getName());
	}

	public static final Date convertDate(String dateStr) {
		try {
			String newDate = dateStr.replaceAll("\\/", "-").replaceAll("\\\\", "-").trim();
			if (newDate.indexOf(" ") == -1) newDate = newDate + " 00:00:00 000";
			else if (newDate.indexOf(" ") == newDate.lastIndexOf(" ")) newDate = newDate + " 000";
			System.out.println(newDate);
			return new SimpleDateFormat(FULL_DATE_ZH_FORMAT).parse(newDate);
		} catch (Exception e) {
			throw new RuntimeException("日期转换错误 ：" + dateStr, e);
		}
	}

	public static void main(String[] args) {

	}
}
